package com.hjx.aes;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * java实现AES256加密解密 依赖说明： bcprov-jdk15-133.jar：PKCS7Padding javabase64-1.3.1.jar：base64 local_policy.jar 和 US_export_policy.jar需添加到%JAVE_HOME%\jre\lib\security中（lib中版本适合jdk1.7）
 */

public class AES256 {

	public static boolean initialized = false;

	public static final String ALGORITHM = "AES/ECB/ZeroBytePadding";

	/**
	 * @param String
	 *            str 要被加密的字符串
	 * @param byte[]
	 *            key 加/解密要用的长度为32的字节数组（256位）密钥
	 * @return byte[] 加密后的字节数组
	 */
	public static byte[] Aes256Encode(String str, byte[] key) {
		initialize();
		byte[] result = null;
		try {
			Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
			SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); // 生成加密解密需要的Key
			cipher.init(Cipher.ENCRYPT_MODE, keySpec);
			result = cipher.doFinal(parseHexStr2Byte(str));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * @param byte[]
	 *            bytes 要被解密的字节数组
	 * @param byte[]
	 *            key 加/解密要用的长度为32的字节数组（256位）密钥
	 * @return String 解密后的字符串
	 */
	public static String Aes256Decode(byte[] bytes, byte[] key) {
		initialize();
		String result = null;
		try {
			Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
			SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); // 生成加密解密需要的Key
			cipher.init(Cipher.DECRYPT_MODE, keySpec);
			byte[] decoded = cipher.doFinal(bytes);
			result = parseByte2HexStr(decoded);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static void initialize() {
		if (initialized)
			return;
		Security.addProvider(new BouncyCastleProvider());
		initialized = true;
	}

	public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	public static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		System.out.println(hexStr+"====hexStr===="+result.length);
		return result;
	}

	public static void main(String[] args) throws Exception {

		String content = "12345678123456781234567812345678";
		String password = "4D616E496E426C61636B2D7A6875786724324234455543453453456677888999";
		System.out.println("明文：" + content);
		System.out.println("key：" + password);

		byte[] encryptResult = AES256.Aes256Encode(content, parseHexStr2Byte(password));
		System.out.println("密文：" + AES256.parseByte2HexStr(encryptResult));

		String decryptResult = AES256.Aes256Decode(encryptResult, parseHexStr2Byte(password));
		System.out.println("解密：" + decryptResult);

		System.out.println(Aes256Decode(parseHexStr2Byte("A1AFC9EC50222C7D46C08992D7E6553A"), parseHexStr2Byte(password)));

		Cipher cipher = Cipher.getInstance("AES/ECB/ZeroBytePadding");
		SecretKeySpec keySpec = new SecretKeySpec(parseHexStr2Byte(password), "AES");

		cipher.init(Cipher.ENCRYPT_MODE, keySpec);
		byte[] bs2 = cipher.doFinal(parseHexStr2Byte(content));
		System.out.println(parseByte2HexStr(bs2));
		System.out.println(parseByte2HexStr(encrypt(content, parseHexStr2Byte(password))));
		System.out.println(parseByte2HexStr(decrypt(parseHexStr2Byte("A1AFC9EC50222C7D46C08992D7E6553A"), parseHexStr2Byte(password))));
	}

	/**
	 * 加密
	 * 
	 * @param content
	 *            需要加密的内容
	 * @param password
	 *            加密密码
	 * @return
	 */
	public static byte[] encrypt(String content, byte[] password) {
		try {
			SecretKeySpec key = new SecretKeySpec(password, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			byte[] byteContent = parseHexStr2Byte(content);
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return result; // 加密
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密
	 * 
	 * @param content
	 *            待解密内容
	 * @param password
	 *            解密密钥
	 * @return
	 */
	public static byte[] decrypt(byte[] content, byte[] password) {
		try {
			SecretKeySpec key = new SecretKeySpec(password, "AES");	
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(content);
			return result; // 加密
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
